<?php

namespace common\components;

use common\components\image\Image;
use yii\base\ErrorException;
use yii\base\Exception;
use \yii\web\UploadedFile;
use Yii;

/**
 * @todo 封装原图的url path
 * 对上传操作进行封装
 *
 * @author zhangchao
 */
class ZUpload extends \yii\base\Component
{

    const TYPE_IMAGE = 'image';

    /**
     * @var ImageMagic
     */
    public $imaGic;

    /**
     * @var 上传文件类型 image video audio
     */
    public $uploadType;

    /**
     * @var 上传文件的路径
     */
    public $path;

    /**
     * @var 宽
     */
    public $width;

    /**
     * @var 高
     */
    public $height;

    /**
     * @var 文件大小
     */
    public $size;

    /**
     * @var 文件属性名
     */
    public $id;

    /**
     * @var 文件
     */
    public $file;

    /**
     * @var 文件数组
     */
    public $fileArray;

    /**
     * @var 文件短连接名称
     */
    public $shortFileName;

    public function __construct($id, array $options = [])
    {
        if (empty($this->imaGic)) {
            $this->imaGic = new Image(Image::IMAGE_IMAGICK);
        }
        if (!empty($id)) {
            $this->id = $id;
            $this->file = UploadedFile::getInstanceByName($id);
        }
        if (empty($options)) {
            return;
        }
        foreach ($options as $key => $val) {
            $this->$key = $val;
        }
    }

    public function fileInit()
    {
        $this->file = UploadedFile::getInstanceByName($this->id);
    }

    /**
     * 1. 生成路径
     * 2. 生成文件名
     * 3. 移动文件
     */
    public function createLocalFile($_path = '' , $createThumb = true)
    {
        $this->createLocalPath($_path);

        $savePath = $this->fileArray['basePath'] . $this->fileArray['path'];
        $this->createFileName();
        $saveFileName = $this->fileArray['shortName'] . '.' . $this->fileArray['extension'];
        $this->fileArray['file_path'] = $savePath . DIRECTORY_SEPARATOR . $saveFileName;
        //是否删除原图片要根据是否生成缩略图来判断
        $this->file->saveAs($savePath . DIRECTORY_SEPARATOR . $saveFileName , !$createThumb);

        //上传缩略图的文件
        if($createThumb){
            $thumbName = $this->fileArray['shortName'] . '_thumb.' . $this->fileArray['extension'];
            $this->file->saveAs($savePath . DIRECTORY_SEPARATOR . $thumbName , true);
            $this->fileArray['thumb_absolutePath'] = $savePath . DIRECTORY_SEPARATOR . $thumbName;
        }
        $this->fileArray['absolutePath'] = $savePath . DIRECTORY_SEPARATOR . $saveFileName;

        return $this->fileArray['file_path'];
    }

    public function createLocalPath($_path = '' , $createThumb = true)
    {
        if (!empty($_path)) {
            $basePath = $_path;
        } else {
            $basePath = Yii::$app->params['upload_img_path'];
        }

        $path = trim($this->path, '\/');
        if (!empty($path)) {
            $path = $path . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d');
        } else {
            $path = date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d');
        }

        //是否要生成缩略图的目录
        if($createThumb){
            $thumb_path = $path.DIRECTORY_SEPARATOR.'thumb';
            $this->fileArray['thumb_path'] = $thumb_path;
            if (!file_exists($basePath . $thumb_path)) {
                mkdir($basePath . $thumb_path, 0777, true);
            }
        }

        if (!file_exists($basePath . $path)) {
            mkdir($basePath . $path, 0777, true);
        }
        $this->fileArray['basePath'] = $basePath;
        $this->fileArray['path'] = $path;

        return $this->fileArray;
    }

    public function createFileName()
    {
        $shortName = $this->shortUrl(md5($this->file->getBaseName() . microtime(true)));
        $extension = $this->file->getExtension();
        $this->fileArray['shortName'] = $shortName[0];
        $this->fileArray['extension'] = $extension;
        return $this->fileArray;
    }

    /**
     * 获取图片的宽 高
     * @return array
     */
    public function getImageGeometry()
    {
        return $this->imaGic->getImageGeometry($this->fileArray['absolutePath']);
    }


    public function createThumb($width, $height, $type = self::IMAGE_THUMB_SCALE)
    {
        return $this->imaGic->thumb($width, $height, $type = self::IMAGE_THUMB_SCALE);
    }

    /**
     * 短连接生成
     * @param $filename
     * @return array
     */
    function shortUrl($filename)
    {
        $key = 'heiguang';
        $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        // 利用md5算法方式生成hash值
        $hex = hash('md5', $filename . $key);
        $hexLen = strlen($hex);
        $subHexLen = $hexLen / 8;

        $output = array();
        for ($i = 0; $i < $subHexLen; $i++) {
            // 将这32位分成四份，每一份8个字符，将其视作16进制串与0x3fffffff(30位1)与操作
            $subHex = substr($hex, $i * 8, 8);
            $idx = 0x3FFFFFFF & (1 * ('0x' . $subHex));

            // 这30位分成6段, 每5个一组，算出其整数值，然后映射到我们准备的62个字符
            $out = '';
            for ($j = 0; $j < 6; $j++) {
                $val = 0x0000003D & $idx;
                $out .= $base32[$val];
                $idx = $idx >> 5;
            }
            $output[$i] = $out;
        }

        return $output;
    }


    public function createUploadFileUrl()
    {
        return DIRECTORY_SEPARATOR . $this->fileArray['path'] . DIRECTORY_SEPARATOR . $this->fileArray['shortName'] . '.' . $this->fileArray['extension'];
    }

    /**
     * 删除本地图片
     * @param $path
     * @return bool
     */
    public function removeFile($path)
    {
        if (is_string($path)) {
            $boole = unlink($path);
            if (!$boole) {
                return false;
            }
            return true;
        }
        $result = false;
        if (is_array($path)) {
            foreach ($path as $val) {
                $result = unlink($val);
            }
        }
        return $result;
    }

}
